# coding=utf8

import sys
import os
import time

__SCRIPT__PATH = os.getcwd()
sys.path.append(__SCRIPT__PATH)

import config
import pymongo


class Storage:
    __mongodb = ''

    __db = ''

    __record = ''

    def __init__(self):
        self.__mongodb = pymongo.Connection(host=config.MONGODB['HOST'], port=config.MONGODB['PORT'])
        self.__db = self.__mongodb.access_server_pingcoo_com_log

    def save(self, records):
        if records is not None:
            __table = 'original_%s' % (time.strftime("%Y%m"))
            __collection = self.__db[__table]
            __collection.insert(records, False)

    def insert(self, record):
        if record is not None:
            self.__record = record
            self.__analysis_api()
            self.__analysis_ad()

    # 统计接口访问情况
    def __analysis_api(self):
        __query = {}
        __query['uuid'] = self.__record['uuid'] if 'uuid' in self.__record else None
        __query['api'] = self.__record['api'] if 'api' in self.__record else None
        __query['date'] = self.__record['date'] if 'date' in self.__record else None
        __query['hour'] = self.__record['hour'] if 'hour' in self.__record else None
        __query['remote_addr'] = self.__record['remote_addr'] if 'remote_addr' in self.__record else None

        __inc = {}
        __inc['req_nums'] = 1

        __set = {}
        __set['token'] = self.__record['token'] if 'token' in self.__record else None

        __table = 'request_api_%s' % (time.strftime("%Y%m"))
        __collection = self.__db[__table]
        __collection.update(__query, {"$set": __set, "$inc": __inc}, True)

    # 统计广告访问情况
    def __analysis_ad(self):
        if 'adid' in self.__record and self.__record['adid'] is not None:
            __query = {}
            __query['uuid'] = self.__record['uuid'] if 'uuid' in self.__record else None
            __query['adid'] = self.__record['adid'] if 'adid' in self.__record else None
            __query['date'] = self.__record['date'] if 'date' in self.__record else None
            __query['hour'] = self.__record['hour'] if 'hour' in self.__record else None
            __query['remote_addr'] = self.__record['remote_addr'] if 'remote_addr' in self.__record else None

            __inc = {}
            __inc['show_nums'] = 1 if 'api' in self.__record and self.__record['api'] == 'showAdCT' else 0
            __inc['click_nums'] = 1 if 'api' in self.__record and self.__record['api'] == 'clickAdCT' else 0

            __set = {}
            __set['token'] = self.__record['token'] if 'token' in self.__record else None

            __table = 'request_ad_%s' % (time.strftime("%Y%m"))
            __collection = self.__db[__table]
            __collection.update(__query, {"$set": __set, "$inc": __inc}, True)

    def __del__(self):
        self.__mongodb.close()